package com.dianrui.fmi.fragment;

import android.annotation.SuppressLint;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.dianrui.fmi.R;
import com.dianrui.fmi.activity.TransactionRecordActivity;
import com.dianrui.fmi.activity.WithDrawActivity;
import com.dianrui.fmi.adapter.AssetsListAdapter;
import com.dianrui.fmi.adapter.SettlementAdapter;
import com.dianrui.fmi.bean.PositionBean;
import com.dianrui.fmi.event.RfreshAccount;
import com.dianrui.fmi.util.MyUtil;
import com.dianrui.fmi.util.OkHttpUtils;
import com.dianrui.fmi.util.StringUtils;
import com.dianrui.fmi.util.ToastUtil;
import com.dianrui.fmi.util.Url;
import com.google.gson.JsonObject;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


public class AccountFragment extends BaseFragment {
    private AssetsListAdapter delegtionListAdapter;
    private AssetsListAdapter postionListAdapter;
    private SettlementAdapter settlementAdapter;
    private List<PositionBean> mSettlementsList = new ArrayList<>();
    private String type = "1";
    private TextView showAskPrice;
    private List<PositionBean> mPositionList = new ArrayList<>();

    @BindView(R.id.right_img)
    ImageView rightImg;
    @BindView(R.id.emptyView)
    LinearLayout emptyView;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.account_name)
    TextView accountName;
    @BindView(R.id.total)
    TextView total;
    @BindView(R.id.balance)
    TextView balance;
    @BindView(R.id.gross_txt)
    TextView grossTxt;
    @BindView(R.id.equity)
    TextView equity;
    @BindView(R.id.margin)
    TextView margin;
    @BindView(R.id.number)
    TextView number;
    @BindView(R.id.listview)
    ListView listview;

    @BindView(R.id.buy_txt)
    TextView buyTxt;
    @BindView(R.id.buy_line)
    View buyLine;
    @BindView(R.id.tr_txt)
    TextView trTxt;
    @BindView(R.id.tr_line)
    View trLine;
    @BindView(R.id.delegation_txt)
    TextView delegationTxt;
    @BindView(R.id.delegation_line)
    View delegationLine;


    @Override
    public int getContentViewId() {
        return R.layout.frag_account;
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        title.setText(getString(R.string.main_account_txt));
        rightImg.setVisibility(View.GONE);
        rightImg.setImageResource(R.mipmap.assets_right_img);
        if (!StringUtils.isEmpty(spUtils.getString("email"))) {
            accountName.setText(spUtils.getString("email"));
        }
        delegtionListAdapter = new AssetsListAdapter(getActivity(), mPositionList);
        listview.setAdapter(delegtionListAdapter);
        getBalanaceInfo();
        getDelegtionList();



    }

    @Override
    public void getData() {
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            getBalanaceInfo();
            getDelegtionList();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RfreshAccount rfreshAccount) {
        getBalanaceInfo();
        getDelegtionList();
    }

    //获取余额（当前余额和已提现）
    private void getBalanaceInfo() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("is_real", "1");
        OkHttpUtils.getInstance().postWithMemberToken(Url.GETBALACE, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && isAdded()) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                total.setText(jsonObject.optJSONObject("data").optString("total"));
                                equity.setText(jsonObject.optJSONObject("data").optString("equity"));
                                margin.setText(jsonObject.optJSONObject("data").optString("margin"));
                                number.setText(jsonObject.optJSONObject("data").optString("number"));
                                balance.setText(jsonObject.optJSONObject("data").optString("balance"));
                                number.setText(jsonObject.optJSONObject("data").optString("order_count"));
                                grossTxt.setText(jsonObject.optJSONObject("data").optString("gross"));

                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {

                }
            }
        });


    }


    private void getDelegtionList() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("type", "1");
        jsonObject.addProperty("is_real", "1");
        OkHttpUtils.getInstance().postWithMemberToken(Url.SIMULATED_LIST, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && isAdded()) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                if (mPositionList != null) {
                                    mPositionList.clear();
                                }
                                JSONArray jsonArray = jsonObject.optJSONArray("data");
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        PositionBean positionBean = new PositionBean();
                                        positionBean.order_id = jsonArray.optJSONObject(i).optString("order_id");
                                        positionBean.createtime = jsonArray.optJSONObject(i).optString("create_time");
                                        positionBean.price = jsonArray.optJSONObject(i).optString("price");
                                        positionBean.start_price = jsonArray.optJSONObject(i).optString("start_price");
                                        positionBean.number = jsonArray.optJSONObject(i).optString("number");
                                        positionBean.earnings = jsonArray.optJSONObject(i).optString("earnings");
                                        positionBean.full_symbol = jsonArray.optJSONObject(i).optString("full_symbol");
                                        positionBean.symbol = jsonArray.optJSONObject(i).optString("symbol");
                                        positionBean.number = jsonArray.optJSONObject(i).optString("number");
                                        positionBean.name = jsonArray.optJSONObject(i).optString("name");
                                        positionBean.direction = jsonArray.optJSONObject(i).optString("direction");
                                        positionBean.service_charge = jsonArray.optJSONObject(i).optString("service_charge");
                                        positionBean.mix_price = jsonArray.optJSONObject(i).optString("mix_price");
                                        positionBean.postion = jsonArray.optJSONObject(i).optString("overnight_fee");
                                        positionBean.total = jsonArray.optJSONObject(i).optString("total");
                                        mPositionList.add(positionBean);
                                    }
                                    if (delegtionListAdapter != null) {
                                        delegtionListAdapter.refresh(mPositionList);
                                    }
                                    listview.setVisibility(View.VISIBLE);
                                    emptyView.setVisibility(View.GONE);
                                } else {
                                    listview.setVisibility(View.GONE);
                                    emptyView.setVisibility(View.VISIBLE);

                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtil.showToast(getString(R.string.net_error));
                }

            }
        });
    }


    private void getPositionList() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("type", "2");
        jsonObject.addProperty("is_real", "1");
        OkHttpUtils.getInstance().postWithMemberToken(Url.SIMULATED_LIST, jsonObject.toString(),  new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && isAdded()) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                if (mPositionList != null) {
                                    mPositionList.clear();
                                }
                                JSONArray jsonArray = jsonObject.optJSONArray("data");
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        PositionBean positionBean = new PositionBean();
                                        positionBean.order_id = jsonArray.optJSONObject(i).optString("order_id");
                                        positionBean.createtime = jsonArray.optJSONObject(i).optString("create_time");
                                        positionBean.price = jsonArray.optJSONObject(i).optString("price");
                                        positionBean.start_price = jsonArray.optJSONObject(i).optString("start_price");
                                        positionBean.number = jsonArray.optJSONObject(i).optString("number");
                                        positionBean.earnings = jsonArray.optJSONObject(i).optString("earnings");
                                        positionBean.full_symbol = jsonArray.optJSONObject(i).optString("full_symbol");
                                        positionBean.symbol = jsonArray.optJSONObject(i).optString("symbol");
                                        positionBean.number = jsonArray.optJSONObject(i).optString("number");
                                        positionBean.name = jsonArray.optJSONObject(i).optString("name");
                                        positionBean.direction = jsonArray.optJSONObject(i).optString("direction");
                                        positionBean.service_charge = jsonArray.optJSONObject(i).optString("service_charge");
                                        positionBean.mix_price = jsonArray.optJSONObject(i).optString("mix_price");
                                        positionBean.postion = jsonArray.optJSONObject(i).optString("overnight_fee");
                                        positionBean.total = jsonArray.optJSONObject(i).optString("total");
                                        mPositionList.add(positionBean);
                                    }
                                    if (postionListAdapter != null) {
                                        postionListAdapter.refresh(mPositionList);
                                    }

                                    listview.setVisibility(View.VISIBLE);
                                    emptyView.setVisibility(View.GONE);

                                } else {
                                    listview.setVisibility(View.GONE);
                                    emptyView.setVisibility(View.VISIBLE);


                                }
                            } else {

                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtil.showToast(getString(R.string.net_error));
                }

            }
        });
    }


    private void getSettlementList() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("type", "3");
        jsonObject.addProperty("is_real", "1");
        OkHttpUtils.getInstance().postWithMemberToken(Url.SIMULATED_LIST, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && isAdded()) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                if (mSettlementsList != null) {
                                    mSettlementsList.clear();
                                }
                                JSONArray jsonArray = jsonObject.optJSONArray("data");
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        PositionBean positionBean = new PositionBean();
                                        positionBean.order_id = jsonArray.optJSONObject(i).optString("order_id");
                                        positionBean.createtime = jsonArray.optJSONObject(i).optString("create_time");
                                        positionBean.price = jsonArray.optJSONObject(i).optString("price");
                                        positionBean.end_time = jsonArray.optJSONObject(i).optString("end_time");
                                        positionBean.number = jsonArray.optJSONObject(i).optString("number");
                                        positionBean.earnings = jsonArray.optJSONObject(i).optString("earnings");
                                        positionBean.start_price = jsonArray.optJSONObject(i).optString("start_price");
                                        positionBean.full_symbol = jsonArray.optJSONObject(i).optString("full_symbol");
                                        positionBean.symbol = jsonArray.optJSONObject(i).optString("symbol");
                                        positionBean.name = jsonArray.optJSONObject(i).optString("name");
                                        positionBean.number = jsonArray.optJSONObject(i).optString("number");
                                        positionBean.service_charge = jsonArray.optJSONObject(i).optString("service_charge");
                                        positionBean.mix_price = jsonArray.optJSONObject(i).optString("mix_price");
                                        positionBean.direction = jsonArray.optJSONObject(i).optString("direction");
                                        positionBean.postion = jsonArray.optJSONObject(i).optString("overnight_fee");
                                        positionBean.margin = jsonArray.optJSONObject(i).optString("margin");
                                        positionBean.total = jsonArray.optJSONObject(i).optString("total");
                                        mSettlementsList.add(positionBean);
                                    }
                                    if (settlementAdapter != null) {
                                        settlementAdapter.refresh(mSettlementsList);
                                    }
                                    listview.setVisibility(View.VISIBLE);
                                    emptyView.setVisibility(View.GONE);


                                } else {
                                    listview.setVisibility(View.GONE);
                                    emptyView.setVisibility(View.VISIBLE);
                                }
                            } else {

                            }

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    @SuppressLint("InflateParams")
    private void showClose(final String id) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.RcDialog);
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.close_asks, null);
        final AlertDialog dialog = builder.create();
        dialog.setView(view);
        TextView cancel_dialog_ask = view.findViewById(R.id.cancel_dialog_ask);
        final TextView yes_dialog_ask = view.findViewById(R.id.yes_dialog_ask);
        cancel_dialog_ask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        yes_dialog_ask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                ClosePostion(id);
            }
        });
        if (!MyUtil.getActivity(dialog.getContext()).isFinishing()) {
            dialog.show();
        }
    }

    @SuppressLint("InflateParams")
    private void showAskPriceDialog(String price) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.RcDialog);
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_ask_price, null);
        final AlertDialog dialog = builder.create();
        dialog.setView(view);
        TextView cancel_dialog_ask = view.findViewById(R.id.cancel_dialog_ask);
        final TextView yes_dialog_ask = view.findViewById(R.id.yes_dialog_ask);
        showAskPrice = view.findViewById(R.id.show_ask_price);
        showAskPrice.setText(price);
        Button askPriceMinues = view.findViewById(R.id.ask_price_minues);
        Button askPriceAdd = view.findViewById(R.id.ask_price_add);
        askPriceMinues.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                float num41 = StringUtils.toFloat(showAskPrice.getText().toString());
                if (num41 > 0.01) {
                    num41 -= 0.001;
                }
                showAskPrice.setText(MyUtil.formatBy2Float(num41, 3) + "");
            }
        });

        askPriceAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                float num5 = StringUtils.toFloat(showAskPrice.getText().toString());
                num5 += 0.001;
                showAskPrice.setText(MyUtil.formatBy2Float(num5, 3) + "");
            }
        });

        cancel_dialog_ask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        yes_dialog_ask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                AskPirce();
            }
        });
        if (!MyUtil.getActivity(dialog.getContext()).isFinishing()) {
            dialog.show();
        }
    }

    private void ClosePostion(String id) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("order_id", id);
        jsonObject.addProperty("is_real", "1");
        OkHttpUtils.getInstance().postWithMemberToken(Url.CLOSE, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (null != jsonObject) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                ToastUtil.showToast(jsonObject.optString("message"));
                                getBalanaceInfo();
                                getPositionList();
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }
        });

    }

    private void AskPirce() {

    }


    @OnClick({R.id.right_img,R.id.account_layout, R.id.deposit, R.id.withdraw, R.id.buy_layout, R.id.tr_layout, R.id.delegation_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.right_img:
                JumpActivitys(TransactionRecordActivity.class);
                break;
            case R.id.account_layout:
                //JumpActivitys(AccountInfoActivity.class);
                break;

            case R.id.deposit:
                AlertDialog.Builder builder1 = new AlertDialog.Builder(getActivity(), R.style.RcDialog);
                View view2 = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_account_ask, null);
                final AlertDialog dialog1 = builder1.create();
                dialog1.setView(view2);
                final TextView yes_dialog = view2.findViewById(R.id.yes_dialog_ask);

                yes_dialog.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog1.dismiss();

                    }
                });
                if (!MyUtil.getActivity(dialog1.getContext()).isFinishing()) {
                    dialog1.show();
                }
                break;
            case R.id.withdraw:
                JumpActivitys(WithDrawActivity.class);
                break;
            case R.id.delegation_layout:

                delegationTxt.setTextColor(getResources().getColor(R.color.red1));
                delegationLine.setVisibility(View.VISIBLE);
                buyTxt.setTextColor(getResources().getColor(R.color.black_333333));
                buyLine.setVisibility(View.INVISIBLE);
                trTxt.setTextColor(getResources().getColor(R.color.black_333333));
                trLine.setVisibility(View.INVISIBLE);
                type = "1";
                delegtionListAdapter = new AssetsListAdapter(getActivity(), mPositionList);
                listview.setAdapter(delegtionListAdapter);
                getDelegtionList();
                break;
            case R.id.buy_layout:

                delegationTxt.setTextColor(getResources().getColor(R.color.black_333333));
                delegationLine.setVisibility(View.INVISIBLE);
                buyTxt.setTextColor(getResources().getColor(R.color.red1));
                buyLine.setVisibility(View.VISIBLE);
                trTxt.setTextColor(getResources().getColor(R.color.black_333333));
                trLine.setVisibility(View.INVISIBLE);
                type = "2";
                postionListAdapter = new AssetsListAdapter(getActivity(), mPositionList);
                listview.setAdapter(postionListAdapter);
                getPositionList();
                postionListAdapter.setOnButtonClickListener(new AssetsListAdapter.CloseClickListener() {
                    @Override
                    public void onPostionsListCloseClick(String id) {
                        showClose(id);

                    }

                    @Override
                    public void onAskPriceClick(String price) {
                        showAskPriceDialog(price);
                    }
                });
                break;
            case R.id.tr_layout:
                buyTxt.setTextColor(getResources().getColor(R.color.black_333333));
                buyLine.setVisibility(View.INVISIBLE);
                trTxt.setTextColor(getResources().getColor(R.color.red1));
                trLine.setVisibility(View.VISIBLE);
                delegationTxt.setTextColor(getResources().getColor(R.color.black_333333));
                delegationLine.setVisibility(View.INVISIBLE);
                settlementAdapter = new SettlementAdapter(getActivity(), mSettlementsList);
                listview.setAdapter(settlementAdapter);
                getSettlementList();
                break;


            default:
                break;
        }
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
